package cn.com.yang.net;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;  

/**
 * 
 * TODO 配置RestTemplate
 * @author yangyijin
 * @since 2024年7月24日-下午2:18:51
 */
@Configuration  
public class RestClientConfig {  

    @Bean  
    public RestTemplate restTemplate() {  
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(30, TimeUnit.SECONDS);  
        CloseableHttpClient httpClient = HttpClients.custom()  
                .setConnectionManager(connectionManager)  
                .setDefaultRequestConfig(RequestConfig.custom()  
                        .setConnectTimeout(5000) // 连接超时时间，单位毫秒  
                        .setSocketTimeout(5000)  // 读取超时时间，单位毫秒  
                        .build())  
                .build();  

        return new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));  
    }  
    
    
    
    @Value("${rest.template.connect-timeout:60000}")  
    private int connectTimeout;  
  
    @Value("${rest.template.read-timeout:60000}")  
    private int readTimeout;  
  
    @Bean ("restTemplate2") 
    public RestTemplate restTemplate2() {  
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();  
        requestFactory.setConnectTimeout(connectTimeout);  
        requestFactory.setReadTimeout(readTimeout);  
        return new RestTemplate(requestFactory);  
    }  
    // SimpleClientHttpRequestFactory 默认超时时间-1
    @Bean  ("restTemplate3")  
    public RestTemplate restTemplate3(RestTemplateBuilder builder) {  
        // 使用RestTemplateBuilder来构建RestTemplate，这样可以轻松地设置请求工厂和其他选项  
        return builder  
            .setConnectTimeout(Duration.ofMillis(5000)) // 设置连接超时  
            .setReadTimeout(Duration.ofMillis(5000)) // 设置读取超时  
            .build();  
    }  
}
